/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ddnsserver;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.*;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 *
 * @author Do Viet Trung
 */
public class SocketServer implements Runnable
{
    private String DatabasePath;
    private ServerSocket SockServer;
    private int Port;
    private JTextArea txtMessage;
    private JList listUsers;
    private static Writer out;
    private ArrayList<AccountInfo> Database;
    Thread t;
    public SocketServer(int port, JTextArea txtMsg, JList lst) throws Exception
    {
        Port = port;
        listUsers = lst;
        txtMessage = txtMsg;
        SockServer = new ServerSocket(port);
        System.out.println("Create");
        DatabasePath = "Data/Accounts.xml";
        Database = new ArrayList<AccountInfo>();
        loadDatabase();
        t = new Thread(this);

    }
    private void loadDatabase()
    {
        try
        {
            AccountXML handle = new AccountXML();
            SAXParserFactory factory = SAXParserFactory.newInstance();
            out = new OutputStreamWriter(System.out,"UTF8");
            SAXParser saxParse = factory.newSAXParser();
            saxParse.parse(new File(DatabasePath), handle);
            Database = handle.getListAccount();
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(new JFrame(),ex.getMessage());
        }
    }
    public void run()
    {
        try
        {
            System.out.println("Start");
            
            while(true)
            {
                Socket incoming = SockServer.accept();
                System.out.println("New Client");
                SocketClient Client = new SocketClient(incoming, txtMessage, listUsers, Database);
                Client.t.start();
            }
        }

        catch (Exception ex)
        {
            ex.printStackTrace();
            return;
        }

    }
}
